package com.aotimes.yy.demo.act;

import java.util.Date;

import org.eclipse.jetty.util.security.Credential.MD5;

import com.aotimes.yy.demo.utils.ProjectParams;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * @see 管理端的，用户管理Act
 * @since 2016年2月23日
 * @category action
 * @author 杨阳
 */
public class UserAct extends BaseAct {

	public void admin_user() {// 跳转到用户管理界面
		render("admin_user.jsp");
	}

	public void userTable() {// 获得用户管理列表
		String sql = " select * from t_user ";
		String searchKey = getPara("searchKey", "");
		if (!"".equals(searchKey)) {
			sql += " where name like '%" + searchKey + "%' or content like '%" + searchKey + "%' ";
		}
		String json = this.getGridData(sql, "t_user");
		renderJson(json);
	}

	public void addOrUpdateUser() {// 跳转到增加或者是修改页面
		String id = getPara("id", "");
		Record user = new Record();
		if (!"".equals(id)) {
			user = getObjById("t_user", id);
		}
		setAttr("user", user);
		render("addOrUpdateUser.jsp");
	}

	public void saveUser() {
		String id = getPara("id", "");
		String name = getPara("name", "");
		String email = getPara("email", "");
		String password = getPara("password", "");
		String job = getPara("job", "");
		String remark = getPara("remark", "");
		String regname = getPara("regname", "");
		String result = "";
		if ("".equals(id)) {// 表示是增加
			Record user = new Record();
			user.set("id", getUUID());
			user.set("name", name);
			user.set("email", email);
			user.set("job", job);
			user.set("remark", remark);
			user.set("createtime", new Date());
			user.set("password", password);
			user.set("regname", regname);
			if (saveObj("t_user", user)) {
				result = successJson("增加用户成功!");
			} else {
				result = errorJson("增加用户失败，请重试!");
			}
		} else {
			Record user = getObjById("t_user", id);
			user.set("name", name);
			user.set("email", email);
			user.set("job", job);
			user.set("remark", remark);
			if (updateObj("t_user", user)) {
				result = successJson("修改用户成功!");
			} else {
				result = errorJson("修改用户失败，请重试!");
			}
		}
		renderJson(result);
	}

	public void userLogin() {
		String result = errorJson("登陆失败!");
		String regname = getPara("regname");
		String password = getPara("password");
		Record user = Db.findFirst("select * from t_user where regname = ? and password = ?",
				new Object[] { regname, password });
		if (null != user) {
			setSessionAttr(ProjectParams.SESSIONKEY, user);
			result = successJson("登陆成功!");
		}
		renderJson(result);
	}

}
